#include "uartHandle.h"
#include "uart.h"
#include "protocol.h"

static uint16_t rIndex = 0;
static uint16_t wIndex = 0;
static uint16_t r3Index = 0;
static uint16_t w3Index = 0;

static void uartDataHandle(uint8_t data)
{
    static uint8_t status;
    static uint8_t cksum;
    static uint8_t len;
    static uint8_t bufIndex;
    static uint8_t cmd;
    static uint8_t buf[16];
    switch (status)
    {
    case 0:
        status = (data == 0xFA) ? 1 : 0;
        break;
    case 1:
        status = (data == 0xFA) ? 2 : 0;
        break;
    case 2:
        len = data;
        cksum = data;
        status = 3;
        break;
    case 3:
        cmd = data;
        bufIndex = 0;
        cksum += data;
        if (len != 0)
        {
            status = 4;
        }
        else
        {
            status = 5;
        }
        break;
    case 4:
        buf[bufIndex] = data;
        bufIndex++;
        cksum += data;
        if (bufIndex == len)
        {
            status = 5;
        }
        break;
    case 5:
        if (cksum == data) /*所有校验正确*/
        {
            bl602DataHandle(cmd, buf);
        }
        status = 0;
        break;
    default:
        break;
    }
}

void uartUpdate(void)
{
    uint8_t recvBuff[256] = {0};
    wIndex = getRemainRecvBuf();
    if (rIndex != wIndex)
    {
        int16_t len = wIndex - rIndex;
        if (len < 0)
        {
            len += 256;
        }
        
        uint16_t i = 0;
        while (i < len)
        {
            uint16_t index = rIndex + i;
            
            if (index > 255)
            {
                index -= 256;
            }
            recvBuff[i] = g_rx[index];
            uartDataHandle(g_rx[index]);
            i++;
        }
        uart3SendData(recvBuff, len);
        rIndex = wIndex;
    }
    // uart3
    w3Index = getRemainRecv3Buf();
    if (r3Index != w3Index)
    {
        int16_t len = w3Index - r3Index;
        if (len < 0)
        {
            len += 256;
        }
        uint16_t i = 0;
        while (i < len)
        {
            uint16_t index = r3Index + i;
            
            if (index > 255)
            {
                index -= 256;
            }
            recvBuff[i] = g_rx3[index];
            uartDataHandle(g_rx3[index]);
            i++;
        }
        uartSendData(recvBuff, len);
        r3Index = w3Index;
    }
}
